let url = 'https://substatsbd.cess.cloud/block/query/latest';
// url = "http://localhost:8088/sse";


async function main(url, data, cb) {
    try {
        if (!cb || typeof cb != 'function') {
            cb = console.log;
        }
        let options = {
            method: data ? 'post' : 'get',
            headers: {
                'Content-Type': 'text/event-stream'
            }
        };
        if (data) {
            options.body = data;
        }
        const response = await fetch(url, options);
        const reader = response.body.pipeThrough(new TextDecoderStream()).getReader()
        while (true) {
            let { value, done } = await reader.read();
            if (done){
                setTimeout(function () {
                    main(url, data, cb);
                }, 3000);
                break;
            }
            value = value.split('\n').join('').replace('data: ', '');
            try {
                value = JSON.parse(value);
            } catch (e) {

            }
            // console.log(value);
            cb(null, value);
        }
    } catch (e) {
        console.log('出错了')
        console.log(e.message);
        setTimeout(function () {
            main(url, data, cb);
        }, 3000);
        cb(e.message);
    }
}
main(url);